from flask import Blueprint

chat_report = Blueprint('chat_report', __name__)
from Test import db
import json
from utils.tokenUtil import *
import logging


##TODO 调整字段属性
class ChatReport(db.Model):
    __tablename__ = 'chat_report'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, nullable=True)
    question = db.Column(db.String(255), nullable=True)
    content = db.Column(db.String(255), nullable=True)
    status = db.Column(db.Integer, nullable=True)
    create_time = db.Column(db.DateTime, nullable=True)
    update_time = db.Column(db.DateTime, nullable=True)

def to_dict_value(self):
    return {
        'id': self.id,
        'question': self.question,
        # 'content': self.content,
        'status': self.status,
        'create_time': self.create_time
    }

##报告列表
@chat_report.route('/chat_report/list', methods=['GET'])
@token_required
def list_chat_report():
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        query = ChatReport.query.filter_by(user_id=g.user_id)

        query = query.order_by(ChatReport.create_time.desc())
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        data = [to_dict_value(msg) for msg in pagination.items]

        return jsonify({
            'data': {
                'data': data,
                'total': pagination.total,
                'pages': pagination.pages,
                'current_page': pagination.page,
                'per_page': pagination.per_page,
            },
            'message': 'get user message success',
            'status': 200
        })
    except Exception as e:
        logging.error('获取报告失败,错误原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })

##报告详情
@chat_report.route('/chat_report/detail', methods=['POST'])
@token_required
def detail_chat_report():
    try:
        request_data = request.get_json()
        chat_report = ChatReport.query.filter_by(user_id=g.user_id).filter_by(id=request_data['id']).first()
        if chat_report is None:
            return jsonify({
                'data': {},
                'message': 'data not exist',
                'status': 500
            })

        # 标记为已读
        chat_report.status = 1
        chat_report.update_time = datetime.datetime.utcnow()
        db.session.commit()

        data = {
            "id": chat_report.id,
            "question": chat_report.question,
            "content": chat_report.content
        }

        return jsonify({
            'data': data,
            'message': 'success',
            'status': 200
        })
    except Exception as e:
        logging.error('获取用户消息失败,错误原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })



